<?php
declare (strict_types = 1);

namespace app\middleware;

use app\lib\Sign;
use app\model\Account;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $appInfo=(new Account())->getInfo($request->param('app_id'));

        if (!$appInfo){
            return json([
                'code'=>1,
                'data'=>'',
                'msg'=>'无权限访问'
            ],403);
        }
        if ($appInfo['limit_ip']!='*'){
            //ip校验
            $ip=$request->ip();

           if (!in_array($ip,$appInfo['limit_ip'])){
               return json([
                   'code'=>1,
                   'data'=>'',
                   'msg'=>'此Ip禁止访问'
               ],403);
           }
        }

        //有效期校验

        if ($appInfo['off_time']!=0){
            if ($appInfo['off_time']<time()){
                return json([
                    'code'=>1,
                    'data'=>'',
                    'msg'=>'应用已经截止'.date($appInfo['off_time']).'到期'
                ],403);
            }
        }
        //签名校验
        if (!env('app_debug')){
            $params=$request->param();

            if (!Sign::check($params['sign'],$appInfo['secret'],$params)){
                return json([
                    'code'=>1,
                    'data'=>'',
                    'msg'=>'签名校验失败'
                ],403);
            }
        }


        return $next($request);
    }
}
